#include "Utils.h"

int getEndian(const char* p)
{
    if((unsigned char)p[0] == 0xFF && (unsigned char)p[1] == 0xFE)
        return 0;
    else if((unsigned char)p[0] == 0xFE && (unsigned char)p[1] == 0xFF)
        return 1;
    else
        return -1;
}

///大端字节序转为小端字节序，当前大部分笔记本电脑和手机都是小端字节序
void big2little(wchar_t* src, unsigned int size) {
    for (unsigned int iix = 0; iix < size; ++iix, ++src) {
        *src = (((*src) & 0xff00) >> 8) | (((*src) & 0x00ff) << 8);
    }
    return;
}

bool IsBigEndian()
{
    int a = 0x1234;
    char b =  *(char *)&a;  //通过将int强制类型转换成char单字节，通过判断起始存储位置。即等于取b等于a的低地址部分
    if( b == 0x12)
    {
        return true;
    }
    return false;
}


CodeInfo getCodeInfo(const char* ch)
{
    CodeInfo code_info;

    if(ch[0] == 0x00)
    {
        code_info.char_set = "iso-8859-1";
        code_info.offset = 1;
    }
    else if(ch[0] == 0x01)
    {
        code_info.char_set = "UTF-16";
        code_info.endian = getEndian(ch + 1);
        code_info.offset = 3;
    }
    else if(ch[0] == 0x02)
    {
        code_info.char_set = "UTF-16BE";
        code_info.endian = getEndian(ch + 1);
        code_info.offset = 3;
    }
    else if(ch[0] == 0x03)
    {
        code_info.char_set = "UTF-8";
        code_info.offset = 4;
    }
    else
    {
        code_info.char_set = "GBK";
        code_info.offset = 1;
    }

    return code_info;
};

//找到所有小于等于target的数字中的最大数的位置，如果都大于target，返回-1
int getTargetPos(QVector<int>& nums, int target)
{
    int left = 0;
    int right = nums.size() - 1;

    if(target < nums[0])
        return -1;

    while(left <= right)
    {
        int mid = left + (right - left)/2;
        if(nums[mid] == target)
            return mid;
        else if(nums[mid] < target)
        {
            if(mid == nums.size() - 1)
                return mid;
            else if(nums[mid + 1] > target)
                return mid;
            else
                left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return nums.size() - 1;
};
